<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\Camp;
use App\Models\Label;
use Illuminate\Support\Facades\Redis;

class CampService extends BaseService
{
    /**
     * 营地详情
     * @return array
     * @throws BusinessException
     */
    public function detail()
    {
        // 获取数据
        $data = Camp::query()->first();
        if (!$data) {
            $this->throwBusinessException('营地不存在');
        }
        $data->increment('views');
        $data = $data->toArray();

        $data['camp_img'] = storageMulti($data['camp_img']);
        $data['camp_qrcode'] = storage($data['camp_qrcode']);
        $data['buy_notice'] = json_decode($data['buy_notice'], true) ?? [];
        // 标签
        $labelNames = Label::query()->pluck('label_name', 'id') ?? [];
        $labelIds = explode(',', $data['label_ids']);
        $data['label_name'] = [];
        foreach ($labelIds as $labelId) {
            $data['label_name'][] = $labelNames[$labelId] ?? '';
        }
        $data['start_time'] = date('Y/m/d', strtotime($data['start_time']));
        $data['end_time'] = date('Y/m/d', strtotime($data['end_time']));
        return $data;
    }

    /**
     * 天气信息
     * @param $cityCode
     * @return mixed
     * @throws BusinessException
     */
    public function weatherInfo($cityCode)
    {
        // 获取缓存
        $key = 'camp:weather_info';
        if (Redis::exists($key)) {
            return json_decode(Redis::get($key), true) ?? [];
        }

        $url = 'https://restapi.amap.com/v3/weather/weatherInfo?city=' . $cityCode . '&key=e1c6788d5cdf46cac32965558f6d9958';
        $data = curlRequest($url);

        if ($data['status'] != 1) {
            $this->throwBusinessException('获取天气信息失败');
        }

        // 设置缓存
        Redis::set($key, 3600 * 6, json_encode($data['lives'][0]));

        return $data['lives'][0];
    }
}
